﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Hinacom.Scheduler.Manager.Controls
{
    public partial class IntervalControl : UserControl
    {
        public IntervalControl()
        {
            InitializeComponent();
            drpIntervalUnit.DataSource = IntervalUnit.Units;
        }

        public TimeSpan Interval
        {
            get
            {
                IntervalUnit unit = (IntervalUnit)drpIntervalUnit.SelectedItem;
                if (unit == null) return new TimeSpan(0);
                int v = Convert.ToInt32(nmbIntervalValue.Value);
                if (v <= 0) return new TimeSpan(0);
                return new TimeSpan(unit.Weight * v);
            }
            set
            {
                int val = 0;
                IntervalUnit unit = null;
                if (value.Ticks > 0)
                {
                    foreach (IntervalUnit u in IntervalUnit.Units)
                    {
                        double v = Convert.ToDouble(value.Ticks) / u.Weight;

                        val = Convert.ToInt32(v);
                        unit = u;

                        if (v >= 1 && (v % 1) == 0)
                            break;
                    }
                }

                if (unit == null)
                    unit = IntervalUnit.Units[0];

                nmbIntervalValue.Value = val;
                drpIntervalUnit.SelectedItem = unit;
            }
        }


        private class IntervalUnit
        {
            public string Display { get; set; }
            public long Weight { get; set; }
            private static IntervalUnit[] _units;
            public static IntervalUnit[] Units
            {
                get
                {
                    if (_units == null)
                        _units = new IntervalUnit[]
                        {
                            new IntervalUnit() { Display = "Hours", Weight = 10000L * 1000 * 60 * 60 },
                            new IntervalUnit() { Display = "Minutes", Weight = 10000L * 1000 * 60 },
                            new IntervalUnit() { Display = "Seconds", Weight = 10000L * 1000 }
                        };
                    return _units;
                }
            }
            public override string ToString()
            {
                return Display;
            }
        }

    }
}
